package com.zzm.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzm.shortlink.admin.common.convention.exception.ClientException;
import com.zzm.shortlink.admin.common.enums.UserErrorCodeEnum;
import com.zzm.shortlink.admin.dao.entity.UserDo;
import com.zzm.shortlink.admin.dao.mapper.UserMapper;
import com.zzm.shortlink.admin.dto.req.UserLoginReqDTO;
import com.zzm.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.zzm.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.zzm.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.zzm.shortlink.admin.dto.resp.UserRespDTO;
import com.zzm.shortlink.admin.service.GroupService;
import com.zzm.shortlink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.zzm.shortlink.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static com.zzm.shortlink.admin.common.constant.RedisCacheConstant.USER_LOGIN_KEY;
import static com.zzm.shortlink.admin.common.enums.UserErrorCodeEnum.*;


/**
 * 疑惑：实现类必须实现接口中的所有方法,这是java语言要求的，但为什么UserServiceImpl并没有实现ServiceImpl的继承类IService的所有方法？
 * 答：实现类必须实现接口中的所有方法这句话是没有问题的，如果出现了这种情况，有两个原因：
 *  1.IService中使用了java8以上的默认方法对方法提供了实现，例如：
 *      default boolean updateById(T entity) {
 *         return SqlHelper.retBool(this.getBaseMapper().updateById(entity));
 *     }
 *     default就是默认方法的关键字
 *  2.MyBatis-Plus 使用了 MyBatis 的动态代理特性，当你调用一个 Mapper 接口或 Service 接口的方法时，MyBatis-Plus 动态地生成一个代理实现来处理这个调用。
 *      这意味着即使你没有在 UserServiceImpl 中实现 updateBatchById 方法，MyBatis-Plus 也会在运行时提供一个实现。
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDo> implements UserService {

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;
    private final GroupService groupService;

    @Override
    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDo> queryWrapper = Wrappers.lambdaQuery(UserDo.class)
                .eq(UserDo::getUsername, username);
        UserDo userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new ClientException(USER_NULL);
        }
        UserRespDTO result = new UserRespDTO();
//        会将 userDO 对象中的匹配的属性值复制到 result 对象中。
        BeanUtils.copyProperties(userDO, result);
        return result;
    }

    /**
     * 判断用户名是否存在
     * @param username 用户名
     * @return 用户名存在返回true 否则返回 false
     */
    @Override
    public Boolean hasUsername(String username) {
        return userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public void register(UserRegisterReqDTO requestParam) {

        if (!hasUsername(requestParam.getUsername())) {
            throw new ClientException(USER_NAME_EXIST);
        }
        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + requestParam.getUsername());
        if (!lock.tryLock()) {
            throw new ClientException(USER_NAME_EXIST);
        }
        try {
            int inserted = baseMapper.insert(BeanUtil.toBean(requestParam, UserDo.class));
            if (inserted < 1) {
                throw new ClientException(USER_SAVE_ERROR);
            }
            userRegisterCachePenetrationBloomFilter.add(requestParam.getUsername());
            groupService.saveGroup(requestParam.getUsername(), "默认分组");
        } catch (DuplicateKeyException ex) {
            throw new ClientException(USER_EXIST);
        } finally {
            lock.unlock();
        }

    }


    /**
     * 用户信息修改
     * @param requestParam
     */
    @Override
    public void update(UserUpdateReqDTO requestParam) {

        LambdaUpdateWrapper<UserDo> updateWrapper = Wrappers.lambdaUpdate(UserDo.class)
                .eq(UserDo::getUsername,requestParam.getUsername());
        baseMapper.update(BeanUtil.toBean(requestParam,UserDo.class),updateWrapper);
    }

    /**
     * 用户登录功能
     * @param requestParam
     */
    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        Wrapper<UserDo> queryWrapper = Wrappers.lambdaQuery(UserDo.class)
                .eq(UserDo::getUsername,requestParam.getUsername())
                .eq(UserDo::getPassword,requestParam.getPassword())
                .eq(UserDo::getDelFlag,0);
        UserDo userDo = baseMapper.selectOne(queryWrapper);
        if(userDo == null) {
            throw new ClientException(USER_NULL);
        }
        Map<Object ,Object> hasLoginMap = stringRedisTemplate.opsForHash().entries(USER_LOGIN_KEY + requestParam.getUsername());
        if (CollUtil.isNotEmpty(hasLoginMap)) {
            String token = hasLoginMap.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    .orElseThrow(() -> new ClientException("用户登录错误"));
            return new UserLoginRespDTO(token);
        }

        /**
         * 将用户登录信息存入redis中
         * 使用key：hash(key,value)的结构来进行存储
         * token采用生成uuid的形式
         * Key: login_用户名
         * Value：
         *  key: token标识
         *  value: JSON字符串(用户信息)
         */

        String uuid = UUID.randomUUID().toString();
        stringRedisTemplate.opsForHash().put(USER_LOGIN_KEY + requestParam.getUsername(),uuid, JSON.toJSONString(userDo));
//        将token过期时间也存到redis中
        stringRedisTemplate.expire(USER_LOGIN_KEY + requestParam.getUsername(),30L, TimeUnit.MINUTES);

        return new UserLoginRespDTO(uuid);

    }

    /**
     * 判断用户是否登录.
     *
     * @param username 用户名
     * @param token 鉴权标识
     * @return 已登录：true 未登录：false
     */
    @Override
    public Boolean checkLogin(String username, String token) {

        return stringRedisTemplate.opsForHash().get(USER_LOGIN_KEY + username,token) != null;
    }

    /**
     * 用户退出登录
     * @param username 用户名
     * @param token 鉴权标识
     */
    @Override
    public void logout(String username, String token) {
        if(checkLogin(username, token)) {
//            将用户信息从redis里面删掉
            stringRedisTemplate.delete(USER_LOGIN_KEY + username);
            return;
        }
        throw new ClientException(USER_NOT_LOGIN);
    }
}
